package net.xujialiang.XTestRPA.Config.SpringSecurityConfig;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import net.xujialiang.XTestRPA.Enum.LogEnum;
import net.xujialiang.XTestRPA.Model.ResultData;
import net.xujialiang.XTestRPA.Service.XRPALogService;
import org.apache.tomcat.util.json.JSONParser;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    XRPALogService logService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String errInfo = "其他错误";
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            errInfo = e.getMessage();
        } else if (e instanceof LockedException) {
            errInfo = "账户被锁定，请联系管理员!";
        } else if (e instanceof CredentialsExpiredException) {
            errInfo = "证书过期，请联系管理员!";
        } else if (e instanceof AccountExpiredException) {
            errInfo = "账户过期，请联系管理员!";
        } else if (e instanceof DisabledException) {
            errInfo = "账户被禁用，请联系管理员!";
        } else {
            log.error("登录失败：", e);
            errInfo = "登录失败!";
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();

        Map<String, Object> ret = new LinkedHashMap<>();
        Gson gson = new Gson();
        String gsonJson = gson.toJson(ResultData.fail(-9999, errInfo));

        printWriter.write(gsonJson);
        printWriter.flush();
        printWriter.close();

    }
}